var event = require('../../../../utils/event.js')
var regeneratorRuntime = require('../../../../lib/js/runtime-module.js')
import config from '../../../../utils/config2'
import util from '../../../../utils/util2'

import Serv from '../walletServ'


let TimerClass=util.TimerClass

let timerObj=null//计时器实例
Page({
  
  /**
   * 页面的初始数据
   */
  data: {
    getBankId:'',
    BankId:'',
    balance: '',//总余额
    timeCount: 0,
    disabled: false,
    countText: '获取验证码',
    isSendMsg: false,
    bankFlag: false,
    bankIndex: '',
    isBtnDisable: true,//下一步按钮是否可用
    step: 0,
    phoneNo: '',
    user_id: '',
    // 表单数据
    verify_code: '',
    password: {},
    total_amount: '',
    linked_acctno: '',
    
    curBankItem: {},
    bankList: [
    ],
  },
  //选择银行弹窗显示隐藏
  getBankId:function(e){
    this.setData({
      BankId:e.detail.value
    })
  },
  toggleShowBank: function () {
    this.setData({bankFlag:!this.data.bankFlag})
  },
  // 选择银行
  selectBank (e) {
    console.log(this.data.bankList)
    
    console.log(e.currentTarget.dataset.index)
    let {bankList = [], bankFlag} = this.data
    let {index} = e.currentTarget.dataset
    this.setData({
      bankIndex: index,
      curBankItem: bankList[index]||{},
      bankFlag: !bankFlag,
      linked_acctno: bankList[index]['linked_acctno']||'',
    })
    console.log(this.data.curBankItem['linked_acctno'])
  },
  
  
  // 获取银行卡列表
  queryLinkedAcct: async function (user_id) {
    //发起请求
    let params = {
      user_id: user_id,
    }
    let {success, msg, data} = await Serv.queryLinkedAcct(params)
    if (!success) {
      wx.showToast({
        title: msg || '',
        icon: 'none',
      })
      return false
    }
    let bankList= data.linked_acctlist || [];
    bankList.map((item,index)=>{
      item.logourl=`${config.ossHost}images/logo/${item.linked_bankcode}.png`
      item.linked_acctno_new=(item.linked_acctno||'').replace(/\d*(\d{4})/, '***************$1')
    
    })
    
    this.setData({
      bankList: bankList || [],//linked_bankcode
      bankIndex:0,
      linked_acctno: bankList[0].linked_acctno

    })
  },
  
  // 查询
  getWalletUser: async function () {
    //发起请求 user_id  user_type
    let {user_id,total_amount}=this.data
    let params = {
      accountId: user_id,
      // appId: '',
    }
    let {success, msg, data} = await Serv.getWalletUser(params)
    
    if (!success) {
      wx.showToast({
        title: msg || '',
        icon: 'none',
      })
      return false
    }
    let {balance=''}=data||{}
    total_amount=balance>100000?100000:balance
    this.setData({balance,total_amount})
  },
  
  // 表单输入
  bindinput: function (e) {
    console.log('bindinput', e.currentTarget.dataset, e.detail)
    let label = e.currentTarget.dataset.label
    let value = e.detail.value
    let {verify_code, password, total_amount, isSendMsg, isBtnDisable, linked_acctno, disabled} = this.data
    let errorMsg = ''
    this.setData({
      [label]: value,
      isBtnDisable
    })
  },
  
  pwdFocus: function (e) {
    let label = e.currentTarget.dataset.label
    // from：当前地址， eventName: 监听定义的事件名
    util.navigateStateChange(this, 'inputDisable')
    wx.navigateTo({
      url: '../../pwdCtrl/pwdCtrl?from=/wallet/cashOutApply/cashOutApply&eventName=onPwdChange' + `&label=${label}`
    })
  },
  //密码控件回调
  pwdCtrlCallback: function () {
  
  },
  
  // 发送验证码
  sendMsg: async function () {
    let {verify_code, password, total_amount, isSendMsg, isBtnDisable, linked_acctno, disabled, user_id, random_key} = this.data
    // 校验表单
    let regMag = {
      mobile: /^1[345789]\d{9}$/,//手机
      idcard: /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,//身份证
      num: /^\d*\.?\d+$/,//数字，可包含小数点
      price: /^\d+(\.\d{1,2})?$/,//价格
      bankcard: /^\d{6,25}$/g,//银行卡号
    }
    // if (!(verify_code !== '' && password !== '' && total_amount !== '')) {
    //   return false
    // }
    console.log(this.data.getBankId)
    let errorMsg = ''
    if (this.data.bankIndex === '') {
      errorMsg = '请选择银行卡'
    }
    
    else if (password&&!password.pwdMw) {
      
      errorMsg = '请输入交易密码'
    }
    else if (total_amount === '') {
      errorMsg = '请输入提现金额'
    }
    else if (!regMag.price.test(total_amount)) {
      errorMsg = '金额只支持数字（最多两位小数）'
    }
    if (errorMsg) {
      
      wx.showToast({
        title: errorMsg || '',
        icon: 'none',
      })
      return false
    }

    
    if(timerObj==null){//计时器实例化
      timerObj=new TimerClass(60, (timeCount,countText) => {
        let disabled = countText!=='获取验证码'
        this.setData({
          timeCount: timeCount,
          disabled: disabled,
          countText: countText,
        })
      })
    }
    // 计时器状态
    if (timerObj.disabled) {
      return false
    }
    timerObj.start()
    console.log('sendMsg', password)
    //发起请求
    let params = {
      linked_acctno: linked_acctno,
      //linked_agrtno: '',
      // funds_flag: '',
      orderInfo: {//total_amount   order_info  postscript
        total_amount: total_amount,
        //order_info: '',
        postscript: '智美置家钱包余额提现',
      },
      payerInfo: {//payer_type  payer_id  payer_accttype  password   random_key
        payer_type: 'USER',
        payer_id: user_id,
        password: password.pwdMw || '',
        random_key: password.randomKey || '',
      },
    }
    let {success, msg, data} = await Serv.withdrawal(params)
    if (!success) {
      timerObj.stop()
      this.setData({isSendMsg:false})
      wx.showToast({
        title: msg || '',
        icon: 'none',
      })
      return false
    }else{
      this.setData({ isSendMsg: true })
    }
  },
  
  // 发送验证码(提现申请)

  // 提现申请确认
  submit: async function () {
    
    let {verify_code, password, total_amount, isSendMsg, isBtnDisable, linked_acctno, disabled, user_id} = this.data
    //payer_type   payer_id  total_amount   verify_code
    let params = {
      payer_type: 'USER',
      payer_id: user_id,
      total_amount: total_amount,
      verify_code: verify_code,
    }
    //发起请求
    
    let {success, msg, data} = await Serv.tradeSecondSmsValid(params)
    if(success){
      wx.showModal({
        title: '提示',
        content: '操作成功',
        showCancel: false,
        complete: (res) => {
          wx.redirectTo({
            url: `../cashOutResult/cashOutResult?id=${data.txn_seqno || ''}`,
          })
        }
      })
    }else{
      wx.showToast({
        title: msg,
        icon:'none'
      })
      console.log(msg)
    }
    
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let user_id = wx.getStorageSync(config.userIdKey)
    let phoneNo = (wx.getStorageSync('walletInfo')||{}).mobile
    // console.log('onLoad user_id',user_id)
    this.setData({user_id, phoneNo})
    this.queryLinkedAcct(user_id)
  
    //监听密码控件输入
    let  that = this
    event.on('onPwdChange', that, function (changedData) {
      let {pwdMw = '', label = '', randomKey = '',pwdHash='',pwdlen=0} = changedData
      console.log('DataChanged trigger...', changedData, {
        [label]: pwdMw
      })
      that.setData({
        [label]: {
          pwdMw: pwdMw,
          randomKey: randomKey,
          pwdHash: pwdHash,
          pwdlen: pwdlen,
          pwdMw_new: pwdMw.substr(0,pwdlen),
        },
      })
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },
  
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  this.getWalletUser()
  },
  
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },
  
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var that = this
    //取消监听
    event.remove('onPwdChange', that)
  },
  
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },
  
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },
  
  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {
  //
  // },
  
})
